package com.fdhwws.web.service.impl;

import com.fdhwws.web.dao.ChatRoomMsgDao;
import com.fdhwws.web.dao.impl.ChatRoomMsgDaoImpl;
import com.fdhwws.web.domain.ChatRoom;
import com.fdhwws.web.domain.ChatRoomMsg;
import com.fdhwws.web.domain.User;
import com.fdhwws.web.entity.AjaxResult;
import com.fdhwws.web.service.ChatRoomMsgService;
import com.fdhwws.web.service.ChatRoomService;
import com.fdhwws.web.util.InfoSecurityUtil;
import com.mysql.cj.util.StringUtils;

import java.sql.Timestamp;
import java.util.List;

public class ChatRoomMsgServiceImpl implements ChatRoomMsgService {
    private final ChatRoomMsgDao chatRoomMsgDao = new ChatRoomMsgDaoImpl();
    private final ChatRoomService chatRoomService = new ChatRoomServiceImpl();

    @Override
    public AjaxResult getChatRoomMsg(Integer roomId, String pwd) {
        Boolean b = chatRoomService.verifyChatRoom(roomId, pwd);
        if (!b) {
            return AjaxResult.error("密码错误或者房间无效!", null);
        }
        return AjaxResult.success("查询成功", chatRoomMsgDao.selectListByRoomId(roomId));
    }

    @Override
    public AjaxResult sendMessage(Integer roomId, String pwd, User user, String message) {
        AjaxResult chatRoomByRoomId = chatRoomService.getChatRoomByRoomId(roomId);
        if (chatRoomByRoomId.isSuccess()) {
            ChatRoom chatRoom = (ChatRoom) chatRoomByRoomId.data;
            if (!chatRoom.getValid()) {
                return AjaxResult.error("房间无效", null);
            }
            if (chatRoom.getAccess() == 1 ||
                    (chatRoom.getAccess() == 0 && !StringUtils.isNullOrEmpty(pwd) && chatRoom.getPassword().equals(InfoSecurityUtil.encrypt(pwd)))) {
                int insert = chatRoomMsgDao.insert(new ChatRoomMsg(null, user.getId(), roomId, user.getUsername(), message, new Timestamp(System.currentTimeMillis()), true));
                if (insert > 0) {
                    return AjaxResult.success("发送成功", chatRoomMsgDao.selectListByRoomId(roomId));
                } else {
                    return AjaxResult.error("发送失败", null);
                }
            } else {
                return AjaxResult.error("密码错误!", null);
            }
        } else {
            return AjaxResult.error("无此房间", null);
        }
    }
}
